package org.iot.iotserver.netty.config;

import cn.hutool.cron.CronUtil;
import cn.hutool.cron.task.Task;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

/**
 * Netty 嵌入 Servlet 容器启动监听器
 */
public class NettyServletContextBootstrapListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        CronUtil.schedule("*/30 * * * * ?", (Task) () -> {
            NettyConstant.DEVICE_CACHE.forEach(device -> {
                long now = System.currentTimeMillis();
                // 超时
                if(now - device.getLastAccessTime() > NettyConstant.HEART_BEAT_TIMEOUT) {
                    device.setStatus(NettyConstant.DeviceStatus.IN_ACTIVE);
                    NettyConstant.CHANNELS.stream()
                            .filter(channel -> device.getId().equals(channel.attr(NettyConstant.DEVICE_KEY).get()))
                            .forEach(channel -> channel.close());
                }
            });
        });
        CronUtil.start(true);
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        CronUtil.stop();
    }
}
